﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS.Core.CommonFilter;
using Kingdee.BOS.Core.CommonFilter.PlugIn;
using Kingdee.BOS.Core.CommonFilter.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Model.CommonFilter;
using Kingdee.BOS.Model.ListFilter;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Resource;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.K3.SCM.Stock.Report.PlugIn;

namespace RK.FilterPlugin.CommonTest
{
    [Description("扩展_安全库存预警报表过滤界面插件"), HotUpdate]
    public class DzStockWarnSafeStockRptFilter : DzStockFilterCommon
    {
        private string selectNodeId;
        private bool isLoaded;
        public override void OnLoad(EventArgs e)
        {
            this.View.StyleManager.SetVisible("FTab_P21", null, false);
            base.OnLoad(e);
        }
        public override void OnInitialize(InitializeEventArgs e)
        {
            base.OnInitialize(e);
        }
        public override void FireBeforeSelectTreeNodeScheme(TreeNodeArgs e)
        {
            selectNodeId = e.NodeId;
            base.FireBeforeSelectTreeNodeScheme(e);
        }
        public override void TreeNodeClick(TreeNodeArgs e)
        {
            base.TreeNodeClick(e);
            InitStkOrgId();
            isLoaded = true;
        }

        public override void AfterBindData(EventArgs e)
        {
            base.AfterBindData(e);
            if (!this.Context.IsMultiOrg)
            {
                this.View.StyleManager.SetEnabled("FStockOrgId", null, false);
                Dictionary<string, object> customParameters = this.View.ParentFormView.OpenParameter.GetCustomParameters();
                if (customParameters.Keys.Contains("DefaultSelectSchemeID") && customParameters["DefaultSelectSchemeID"].ToString().Equals(selectNodeId))
                {
                    SetSafeStockWarnConsoleValue(customParameters);
                }
            }
        }
        public override void BeforeF7Select(BeforeF7SelectEventArgs e)
        {
            base.BeforeF7Select(e);
            ListShowParameter val = e.DynamicFormShowParameter as ListShowParameter;
            string fieldKey = e.FieldKey.ToLowerInvariant();
            if (fieldKey == null || (fieldKey != "FMATERIALFROM" && fieldKey != "FMATERIALTO"))
            {
                return;
            }
            if (selOrgId.Length == 0)
            {
                this.View.ShowMessage(ResManager.LoadKDString("请先选择库存组织！", "004024030000910", (SubSystemType)5, new object[0]), 0);
                e.Cancel = true;
                return;
            }
            if (!(e.BaseDataField as BaseDataField).OrgFieldKey.IsNullOrEmptyOrWhiteSpace())
            {
                val.MutilListUseOrgId = selOrgId;
            }
            e.IsShowUsed = false;
        }
        public override void BeforeFilterGridF7Select(BeforeFilterGridF7SelectEventArgs e)
        {
            base.BeforeFilterGridF7Select(e);
            switch (e.FieldKey.ToLowerInvariant())
            {
                case "FMATERIALNUMBER":
                case "FMATERIALNAME":
                    e.IsShowUsed = false;
                    break;
            }
            SetFilterGridMuliOrg(e);
        }
        public override void BeforeSetItemValueByNumber(BeforeSetItemValueByNumberArgs e)
        {
            base.BeforeSetItemValueByNumber(e);
            string a = e.BaseDataFieldKey.ToUpperInvariant();
            if (a != null && (a == "FMATERIALFROM" || a == "FMATERIALTO" || a == "FMATERIALNUMBER" || a == "FMATERIALNAME"))
            {
                e.IsShowUsed = false;
            }
        }
        public override void OnParseSetting(OnParseSettingEventArgs e)
        {
            if (!isLoaded)
            {
                return;
            }
            FilterModel val = this.View.Model as FilterModel;
            if (val == null)
            {
                return;
            }
            bool flag = Convert.ToBoolean(this.Model.GetValue("FSafeStockCK"));
            if (!flag)
            {
                val.ColumnObject.FieldList.Find(m => m.FieldName.ToUpperInvariant() == "FSAFEBASEQTY").Visible = false;
                val.ColumnObject.FieldList.Find((ColumnField m) => m.FieldName.ToUpperInvariant() == "FSAFESTOCKQTY").Visible = false;
                val.ColumnObject.FieldList.Find((ColumnField m) => m.FieldName.ToUpperInvariant() == "FDIFFERECEBASEQTY").Visible = (false);
                val.ColumnObject.FieldList.Find((ColumnField m) => m.FieldName.ToUpperInvariant() == "FDIFFERECESTOCKQTY").Visible = (false);
                val.ColumnObject.FieldList.Find((ColumnField m) => m.FieldName.ToUpperInvariant() == "FDIFFERECERATE").Visible = (false);
            }
            if (!Convert.ToBoolean(this.Model.GetValue("FMaxStockCK")))
            {
                List<ColumnField> list = val.ColumnObject.FieldList.FindAll((ColumnField m) => m.FieldName.ToUpperInvariant().Contains("FMAX"));
                if (list != null && list.Count > 0)
                {
                    foreach (ColumnField item in list)
                    {
                        item.Visible = (false);
                    }
                }
            }
            bool flag2 = Convert.ToBoolean(this.Model.GetValue("FMinStockCK"));
            if (!flag2)
            {
                List<ColumnField> list2 = val.ColumnObject.FieldList.FindAll((ColumnField m) => m.FieldName.ToUpperInvariant().Contains("FMIN"));
                if (list2 != null && list2.Count > 0)
                {
                    foreach (ColumnField item2 in list2)
                    {
                        item2.Visible = (false);
                    }
                }
            }
            if (!Convert.ToBoolean(this.Model.GetValue("FPurOrderZaituCK")))
            {
                val.ColumnObject.FieldList.Find((ColumnField m) => m.FieldName.ToUpperInvariant() == "FPURSAFEBASEQTY").Visible = (false);
                val.ColumnObject.FieldList.Find((ColumnField m) => m.FieldName.ToUpperInvariant() == "FPURSAFESTOCKQTY").Visible = (false);
                val.ColumnObject.FieldList.Find((ColumnField m) => m.FieldName.ToUpperInvariant() == "FPURMINBASEQTY").Visible = (false);
                val.ColumnObject.FieldList.Find((ColumnField m) => m.FieldName.ToUpperInvariant() == "FPURMINSTOCKQTY").Visible = (false);
                return;
            }
            if (!flag)
            {
                val.ColumnObject.FieldList.Find((ColumnField m) => m.FieldName.ToUpperInvariant() == "FPURSAFEBASEQTY").Visible = (false);
                val.ColumnObject.FieldList.Find((ColumnField m) => m.FieldName.ToUpperInvariant() == "FPURSAFESTOCKQTY").Visible = (false);
            }
            if (!flag2)
            {
                val.ColumnObject.FieldList.Find((ColumnField m) => m.FieldName.ToUpperInvariant() == "FPURMINBASEQTY").Visible = (false);
                val.ColumnObject.FieldList.Find((ColumnField m) => m.FieldName.ToUpperInvariant() == "FPURMINSTOCKQTY").Visible = (false);
            }
        }
        public override void ToolBarItemClick(BarItemClickEventArgs e)
        {
            switch (e.BarItemKey.ToUpperInvariant())
            {
                case "SAVESCHEME":
                case "SAVEASSCHEME":
                    if (!isHasCheckCKBox())
                    {
                        this.View.ShowMessage(ResManager.LoadKDString("请至少选择一项预警类型!", "004024030034426", (SubSystemType)5, new object[0]), (MessageBoxType)0);
                        e.Cancel = true;
                        return;
                    }
                    if (!CheckPurDate())
                    {
                        this.View.ShowMessage(ResManager.LoadKDString("采购在途到货日期起始日期不能大于截止日期！", "004024000018585", (SubSystemType)5, new object[0]), (MessageBoxType)0);
                        e.Cancel = true;
                        return;
                    }
                    break;
            }
            base.ToolBarItemClick(e);
        }
        public override void ButtonClick(ButtonClickEventArgs e)
        {
            base.ButtonClick(e);
            string a = e.Key.ToUpperInvariant();
            if (a == null || a != "FBTNOK")
            {
                return;
            }
            string errMsg = string.Empty;
            if (!OkValidate(out errMsg))
            {
                if (errMsg.Contains("\n"))
                {
                    this.View.ShowMessage(errMsg, 0, ResManager.LoadKDString("过滤条件不规范，请修改过滤条件。", "004024030002407", (SubSystemType)5, new object[0]), 0);
                }
                else
                {
                    this.View.ShowMessage(errMsg, 0, "", 0);
                }
                e.Cancel = true;
            }
        }
        public override void DataChanged(DataChangedEventArgs e)
        {
            if (e.Field.Key.ToUpperInvariant().Equals("FSTOCKORGID"))
            {
                selOrgId = e.NewValue.ToString();
                SetDctSelOrgId();
            }
            base.DataChanged(e);
        }

        private bool OkValidate(out string errMsg)
        {
            bool result = true;
            StringBuilder stringBuilder = new StringBuilder();
            if (selOrgId.Length == 0 && this.View.Model.GetValue("FStockOrgId") != null && this.View.Model.GetValue("FStockOrgId").ToString().Trim().Length > 0)
            {
                selOrgId = this.View.Model.GetValue("FStockOrgId").ToString();
            }
            if (selOrgId.Length == 0)
            {
                stringBuilder.AppendLine(ResManager.LoadKDString("请至少选择一个库存组织来进行报表查询。", "004024030000913", (SubSystemType)5, new object[0]));
                result = false;
            }
            if (!isHasCheckCKBox())
            {
                stringBuilder.AppendLine(ResManager.LoadKDString("请至少选择一项预警类型!", "004024030034426", (SubSystemType)5, new object[0]));
                result = false;
            }
            if (!CheckPurDate())
            {
                stringBuilder.AppendLine(ResManager.LoadKDString("采购在途到货日期起始日期不能大于截止日期！", "004024000018585", (SubSystemType)5, new object[0]));
                result = false;
            }
            errMsg = stringBuilder.ToString().Trim('\r', '\n');
            return result;
        }

        private bool CheckPurDate()
        {
            if (Convert.ToBoolean(this.Model.GetValue("FPurOrderZaituCK")))
            {
                DateTime t = Convert.ToDateTime(this.Model.GetValue("FPurBeginDate") ?? "2000-01-01");
                DateTime t2 = Convert.ToDateTime(this.Model.GetValue("FPurEndDate") ?? "2000-01-01");
                if (t > t2)
                {
                    return false;
                }
                return true;
            }
            return true;
        }

        private bool isHasCheckCKBox()
        {
            bool flag = Convert.ToBoolean(this.Model.GetValue("FSafeStockCK"));
            bool flag2 = Convert.ToBoolean(this.Model.GetValue("FMaxStockCK"));
            bool flag3 = Convert.ToBoolean(this.Model.GetValue("FMinStockCK"));
            if (flag || flag2 || flag3)
            {
                return true;
            }
            return false;
        }

        private void SetSafeStockWarnConsoleValue(Dictionary<string, object> custParam)
        {
            if (custParam.Keys.Contains("SourceBillFormId") && custParam["SourceBillFormId"].ToString().Equals("SafeStockWarnConsole"))
            {
                if (!string.IsNullOrEmpty(Convert.ToString(custParam["SourceOrgId"])))
                {
                    SetOrgValue(Convert.ToString(custParam["SourceOrgId"]));
                }
                if (!string.IsNullOrWhiteSpace(Convert.ToString(custParam["SourceWarnId"])))
                {
                    DynamicObject schemeData = GetSchemeData(custParam["SourceWarnId"].ToString());
                    SetFilterGridValue(Convert.ToString(schemeData["FFilterSetting"]));
                }
                JSONObject val = JSONObject.Parse(Convert.ToString(custParam["SourceQFilter"]));
                if (val != null)
                {
                    SetQFilterValue(val);
                }
            }
        }

        private void SetQFilterValue(JSONObject dypara)
        {
            this.Model.SetValue("FRadioGroup", dypara.ContainsKey("FRadioGroup") ? Convert.ToString(dypara["FRadioGroup"]) : null);
            this.Model.SetValue("FDiffereceQty", dypara.ContainsKey("FDiffereceQty") ? Convert.ToDecimal(dypara["FDiffereceQty"]) : 0);
            this.Model.SetValue("FDiffereceRate", dypara.ContainsKey("FDiffereceRate") ? Convert.ToDecimal(dypara["FDiffereceRate"]) : 0);
            this.Model.SetValue("FShowForbidMaterial", dypara.ContainsKey("FShowForbidMaterial") && Convert.ToBoolean(dypara["FShowForbidMaterial"]));
            this.Model.SetValue("FShowNobizMaterial", dypara.ContainsKey("FShowNobizMaterial") && Convert.ToBoolean(dypara["FShowNobizMaterial"]));
        }

        private void SetFilterGridValue(string filterstr)
        {
            ListFilterModel val = new ListFilterModel();
            FormMetadata formMetaData = MetaDataServiceHelper.GetFormMetaData(this.Context, "SCM_SafeStockWarnFilterObject");
            val.FilterObject.FilterMetaData = CommonFilterServiceHelper.GetFilterMetaData(this.Context, "");
            val.SetContext(this.Context, formMetaData.BusinessInfo, formMetaData.BusinessInfo.GetForm().GetFormServiceProvider(false));
            val.InitFieldList(formMetaData, null);
            val.FilterObject.SetSelectEntity(",FBILLHEAD,");
            val.IsolationOrgList = dctSelOrg.Keys.ToList();
            val.FilterObject.Setting = filterstr;
            List<FilterRow> list = new List<FilterRow>();
            foreach (FilterRow filterRow in val.FilterObject.FilterRows)
            {
                switch (filterRow.FilterField.FieldName)
                {
                    case "FStockId.FNumber":
                        filterRow.FilterField.FieldName = "FStockNumber";
                        break;
                    case "FMaterialId.FNumber":
                        filterRow.FilterField.FieldName = "FMaterialNumber";
                        break;
                    case "FMaterialGroup_FNumber.FNumber":
                        filterRow.FilterField.FieldName = "FMaterialGroup_FNumber";
                        break;
                }
                list.Add(filterRow);
            }
            this.CommonFilterModel.FilterObject.FilterRows = (list);
        }

        private DynamicObject GetSchemeData(string warnId)
        {
            FormMetadata val = MetaDataServiceHelper.Load(this.View.Context, "SCM_WarnScheme", true) as FormMetadata;
            return BusinessDataServiceHelper.LoadSingle(this.View.Context, warnId, val.BusinessInfo, null);
        }

        private void SetOrgValue(string orgids)
        {
            this.Model.SetValue("FSTOCKORGID", orgids);
            lstStkOrg = GetPermissionOrg(this.View.ParentFormView.BillBusinessInfo.GetForm().Id);
            GetOrganization(this.Context);
            selOrgId = orgids;
            SetDctSelOrgId();
        }
    }
}
